/*
    Created by IntelliJ IDEA.
    @Auther: gaozhe
    @Date: 2020/5/15 上午 11:14
    
*/
package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import org.apache.commons.beanutils.BeanUtils;
import pojo.ResultInfo;
import pojo.User;
import service.UserService;
import service.serviceImpl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.Map;

@WebServlet("/userLogin")
public class UserLoginServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    ResultInfo resultInfo = new ResultInfo();
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        User user = new User();

        user.setUserName(username);
        user.setPassWord(password);
        System.out.println("login： "+ user);
        //调用service层方法
        User u = userService.userLoginService(user);
        System.out.println(u);
        if (u == null) {
            //用户不存在
            System.out.println("no user");
            resultInfo.setFlag(false);
            resultInfo.setErrorMsg("用户名或密码错误，登录失败！");
        } else {
            System.out.println("have user");
            //用户存在
            //讲用户信息保存在session中，用于之后的存取
            request.getSession().setAttribute("user", u);
            resultInfo.setFlag(true);
            resultInfo.setErrorMsg("ok");
        }
        //将处理结果返回客户端
//        ObjectMapper mapper = new ObjectMapper();
//        String json = mapper.writeValueAsString(resultInfo);
        Gson gson = new Gson();
        String json = gson.toJson(resultInfo);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);
        response.getWriter().close();

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}
